﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using Confcloud.Email.Templates;
using Smarly.Core;
using Smarly.Core.Database;

namespace Smarly.Bussines.Model.Account
{
	public class RepearPassword : ModelStateObject
	{
		[DatabaseValidation("EmailNotExist", "Email не зарегистрирован")]
		[Required(ErrorMessage = "Поле не заполнено")]
		[RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$", ErrorMessage = "Значение email не корректно")]
		public string Email { get; set; }

		public string HashCode { get; set; }
		public string Url { get; set; }

		public RepearPassword Get()
		{
			HashCode = null;
			SqlRepository.ExecuteProcedureReader("RepearPassword_CreateRestoreHash",
																					 new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@email", Type = DbType.String, Value = Email},
			                                     	},
																					 OnSqlInfoMessage,
																					 reader =>
																					 {
																						 while (reader.Read())
																						 {
																							 this.HashCode = reader.GetString("RestoreHashCode");
																						 }
																						 return this;
																					 });

			new RepairPasswordEmail(Email, HashCode, Url.Replace("HASHCODE", HashCode)).Post();

			return this;
		}
	}
}